<template>
  <view class="container">
    <!-- 搜索区域 -->
    <view class="search-area">
      <!-- 分类筛选 -->
      <view class="search-item">
        <picker 
          @change="handleCategoryChange" 
          :range="categoryListWithAll" 
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="searchForm.categoryId">{{ getCategoryName(searchForm.categoryId) }}</text>
            <text v-else class="placeholder">全部分类</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </view>
      
      <!-- 公司选择 -->
      <view class="search-item">
        <picker 
          @change="handleSupplierChange" 
          :range="supplierListWithAll" 
          range-key="name"
        >
          <view class="picker-box">
            <text v-if="searchForm.supplierId">{{ getSupplierName(searchForm.supplierId) }}</text>
            <text v-else class="placeholder">全部公司</text>
            <uni-icons type="bottom" size="14" color="#666"/>
          </view>
        </picker>
      </view>
    </view>

    <!-- 统计卡片 -->
    <!-- <view class="stat-grid">
      <view class="stat-card stat-blue">
        <text class="stat-title">总商品</text>
        <text class="stat-value">{{ statistics.total || 0 }}</text>
        <text class="stat-footer">总计商品数量</text>
      </view>
      <view class="stat-card stat-red">
        <text class="stat-title">库存预警</text>
        <text class="stat-value">{{ statistics.warning || 0 }}</text>
        <text class="stat-footer">需及时处理</text>
      </view>
    </view> -->

    <!-- 商品列表 -->
    <view class="goods-container">
      <view 
        class="goods-item" 
        v-for="(item, index) in goodsList" 
        :key="item.id"
        @tap="handleGoodsClick(item)"
      >
        <view class="goods-info">
          <view class="goods-header">
            <text class="goods-title">{{ item.name }}</text>
            <text :class="['stock-tag', getStockStatusClass(item)]">
              库存: {{ item.stock }}
              <text v-if="isStockWarning(item)" class="warning-text">
                (低于预警值{{ item.warningStock }})
              </text>
            </text>
          </view>
          <view class="goods-detail">
            <text class="price">¥{{ item.purchasePrice }}</text>
            <text class="supplier">公司: {{ item.supplier.name }}</text>
            <text class="category">分类: {{ item.category?.name || '未分类' }}</text>
          </view>
          <!-- <view class="goods-actions">
            <button class="action-btn btn-primary" @click="handlePurchase(item)">
              <uni-icons type="plus" size="14" color="#fff"/>
              <text>进货</text>
            </button>
            <button class="action-btn btn-success" @click="handleSell(item)">
              <uni-icons type="minus" size="14" color="#fff"/>
              <text>卖出</text>
            </button>
            <button class="action-btn btn-default" @click="handleEdit(item)">
              <uni-icons type="compose" size="14" color="#666"/>
              <text>编辑</text>
            </button>
            <button class="action-btn btn-danger" @click="handleDelete(item)">
              <uni-icons type="trash" size="14" color="#ff4d4f"/>
              <text>删除</text>
            </button>
          </view> -->
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="goodsList.length === 0" class="empty-state">
        <uni-icons type="shop" size="64" color="#999"/>
        <text class="empty-text">暂无商品数据</text>
      </view>
    </view>

    <!-- 卖出弹窗 -->
    <uni-popup ref="sellDialog" type="dialog">
      <uni-popup-dialog 
        ref="inputClose" 
        mode="input" 
        :before-close="true" 
        @close="handleSellClose" 
        title="卖出商品" 
        placeholder="请输入卖出数量" 
        @confirm="handleSellConfirm"
      />
    </uni-popup>

    <!-- 进货弹窗 -->
    <uni-popup ref="purchaseDialog" type="dialog">
      <uni-popup-dialog 
        ref="inputClose"
        mode="input"
        title="商品进货"
        :value="purchaseAmount"
        placeholder="请输入进货数量"
        :before-close="true"
        @close="handlePurchaseClose"
        @confirm="handlePurchaseConfirm"
      >
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { onShow, onReachBottom } from '@dcloudio/uni-app'
import { goodsApi } from '@/api/goods'
import { supplierApi } from '@/api/supplier'

// 分类相关
const categoryList = ref([])
const categoryListWithAll = computed(() => {
  return [{ name: '全部分类', id: '' }, ...categoryList.value]
})

// 搜索表单
const searchForm = ref({
  categoryId: '',
  supplierId: ''
})

// 商品名称列表（用于选择）
const goodsNameList = ref([])
// 添加全部选项的商品列表
const goodsNameListWithAll = computed(() => {
  return [{ name: '全部商品', id: '' }, ...goodsNameList.value]
})

// 公司列表
const supplierList = ref([])
// 添加全部选项的公司列表
const supplierListWithAll = computed(() => {
  return [{ name: '全部公司', id: '' }, ...supplierList.value]
})

// 商品列表数据
const goodsList = ref([])

// 统计数据
const statistics = ref({
  total: 0,
  warning: 0
})

// 弹窗控制
const sellDialog = ref(null)
const selectedGoods = ref(null)
const purchaseDialog = ref(null)
const purchaseAmount = ref('')

// 分页参数
const page = ref(1)
const size = ref(10)
const hasMore = ref(true)

// 获取所有商品名称列表
const getGoodsNameList = async () => {
  try {
    const res = await goodsApi.getList({
      page: 1,
      size: 999 // 获取所有商品
    })
    goodsNameList.value = res.list || []
  } catch (error) {
    console.error('获取商品列表失败:', error)
  }
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await goodsApi.getCategories()
    categoryList.value = res || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取分类名称
const getCategoryName = (id) => {
  if (!id) return '全部分类'
  const category = categoryList.value.find(item => item.id === id)
  return category ? category.name : '全部分类'
}

// 处理分类选择
const handleCategoryChange = (e) => {
  const index = e.detail.value
  const category = categoryListWithAll.value[index]
  searchForm.value.categoryId = category ? category.id : ''
  handleSearch()
}

// 获取公司列表
const getSupplierList = async () => {
  try {
    const res = await supplierApi.getList()
    supplierList.value = res.list || []
  } catch (error) {
    console.error('获取公司列表失败:', error)
  }
}

// 获取公司名称
const getSupplierName = (id) => {
  if (!id) return '全部公司'
  const supplier = supplierList.value.find(item => item.id === id)
  return supplier ? supplier.name : '全部公司'
}

// 处理公司选择
const handleSupplierChange = (e) => {
  const index = e.detail.value
  const supplier = supplierListWithAll.value[index]
  searchForm.value.supplierId = supplier ? supplier.id : ''
  handleSearch()
}

// 获取商品列表
const getGoodsList = async () => {
  try {
    const res = await goodsApi.getList({
      categoryId: searchForm.value.categoryId,
      supplierId: searchForm.value.supplierId,
      page: page.value,
      size: size.value
    })
    
    if (page.value === 1) {
      goodsList.value = res.list || []
    } else {
      goodsList.value.push(...(res.list || []))
    }

    // 更新是否有更多数据
    hasMore.value = res.hasMore

    // 更新统计数据
    statistics.value = {
      total: res.total || 0,
      warning: goodsList.value.filter(item => item.stock <= item.warningStock).length
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'error'
    })
  }
}

// 搜索处理
const handleSearch = () => {
  page.value = 1 // 重置页码
  getGoodsList()
}

// 处理进货
const handlePurchase = (goods) => {
  selectedGoods.value = goods
  purchaseAmount.value = '1' // 默认数量为1
  purchaseDialog.value.open()
}

// 处理进货确认
const handlePurchaseConfirm = async (val) => {
  const num = Number(val)
  if (isNaN(num) || num <= 0) {
    uni.showToast({
      title: '请输入有效数字',
      icon: 'none'
    })
    return
  }

  try {
    await goodsApi.purchase({
      quantity: num,
    }, selectedGoods.value.id)

    handlePurchaseClose()
    uni.showToast({
      title: '进货成功',
      icon: 'success'
    })

    // 刷新列表
    getGoodsList()
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

// 处理弹窗关闭
const handlePurchaseClose = () => {
  purchaseDialog.value.close()
  selectedGoods.value = null
  purchaseAmount.value = ''
}

// 处理卖出
const handleSell = (goods) => {
  selectedGoods.value = goods
  sellDialog.value.open()
}

// 确认卖出
const handleSellConfirm = async (val) => {
  const num = Number(val)
  if (isNaN(num) || num <= 0) {
    uni.showToast({
      title: '请输入有效数字',
      icon: 'none'
    })
    return
  }

  if (num > selectedGoods.value.stock) {
    uni.showToast({
      title: '库存不足',
      icon: 'none'
    })
    return
  }

  try {
    await goodsApi.sell({
      // goodsId: selectedGoods.value.id,
      quantity: num,
    }, selectedGoods.value.id)

    handleSellClose()
    uni.showToast({
      title: '卖出成功',
      icon: 'success'
    })

    // 刷新列表
    getGoodsList()
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'error'
    })
  }
}

// 处理弹窗关闭
const handleSellClose = () => {
  sellDialog.value.close()
  selectedGoods.value = null
}

// 编辑商品
const handleEdit = (goods) => {
  uni.navigateTo({
    url: `/pages/goods/add?id=${goods.id}`
  })
}

// 删除商品
const handleDelete = (goods) => {
  uni.showModal({
    title: '提示',
    content: '确定要删除该商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await goodsApi.delete(goods.id)
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          // 刷新列表
          getGoodsList()
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'error'
          })
        }
      }
    }
  })
}

// 判断库存状态
const getStockStatusClass = (goods) => {
  return {
    'stock-warning': isStockWarning(goods),
    'stock-normal': !isStockWarning(goods)
  }
}

// 判断是否库存预警
const isStockWarning = (goods) => {
  return goods.stock <= goods.warningStock
}

// 处理商品点击
const handleGoodsClick = (goods) => {
  uni.navigateTo({
    url: `/pages/stock/detail?id=${goods.id}`
  })
}

// 页面加载时获取数据
onMounted(() => {
  getGoodsNameList() // 获取商品名称列表
  getSupplierList()
  getGoodsList()
})

// 页面显示时刷新数据
onShow(() => {
  getGoodsNameList() // 刷新商品名称列表
  getSupplierList()
  getCategoryList()
  handleSearch()
})

// 触底加载更多
onReachBottom(()=>{
  if (!hasMore.value) {
    uni.showToast({
      title: '没有更多数据了',
      icon: 'none'
    })
    return
  }
  page.value++
  getGoodsList()
})
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
  overflow-y: auto;
}

.search-area {
  padding: 32rpx;
  background-color: #fff;
  display: flex;
  gap: 12px;
}

.search-item {
  flex: 1;
}

.picker-box {
  background-color: #F8FAFC;
  border: 1px solid #E2E8F0;
  border-radius: 8px;
  height: 40px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.placeholder {
  color: #999;
}

.stat-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
  margin-bottom: 16px;
  padding: 16px;
}

.stat-card {
  padding: 20px;
  border-radius: 16px;
  color: #fff;
}

.stat-blue {
  background-color: #4080ff;
}

.stat-red {
  background-color: #ff4d4f;
}

.stat-title {
  font-size: 14px;
  opacity: 0.9;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin: 8px 0;
  display: block;
}

.stat-footer {
  font-size: 12px;
  opacity: 0.8;
}

.category-filter {
  padding: 0 32rpx;
  margin-bottom: 48rpx;
}

.filter-list {
  display: flex;
  gap: 16rpx;
  padding: 8rpx 0;
}

.filter-item {
  padding: 16rpx 32rpx;
  background-color: #fff;
  color: #475569;
  border: none;
  border-radius: 12rpx;
  white-space: nowrap;
  transition: all 0.3s;
}

.filter-item-active {
  background-color: #2563EB;
  color: #fff;
}

.goods-list {
  flex: 1;
  height: 500rpx;
}

.goods-container {
  padding: 0 32rpx;
}

.goods-item {
  background: #fff;
  border-radius: 16px;
  padding: 16px;
  margin-bottom: 12px;
  position: relative;
  border: 1px solid #eee;
}

.goods-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.goods-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.goods-detail {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.price {
  font-size: 20px;
  font-weight: 600;
  color: #ff4d4f;
}

.supplier {
  font-size: 14px;
  color: #666;
}

.category {
  font-size: 24rpx;
  color: #666;
  margin-left: 16rpx;
}

.stock-tag {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 500;
}

.stock-warning {
  background: #fff2f0;
  color: #ff4d4f;
}

.stock-normal {
  background: #f6ffed;
  color: #52c41a;
}

.warning-text {
  font-size: 12px;
  margin-left: 4px;
  opacity: 0.8;
}

.goods-actions {
  display: flex;
  gap: 8px;
}

.action-btn {
  flex: 1;
  height: 32px;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.btn-primary {
  background-color: #4080ff;
  color: #fff;
}

.btn-success {
  background-color: #52c41a;
  color: #fff;
}

.btn-default {
  background-color: #fff;
  border: 1px solid #ddd;
  color: #666;
}

.btn-danger {
  background-color: #fff;
  border: 1px solid #ff4d4f;
  color: #ff4d4f;
}

.btn-primary:active {
  background-color: #2b5fdb;
}

.btn-success:active {
  background-color: #389e0d;
}

.btn-default:active {
  background-color: #f5f5f5;
}

.btn-danger:active {
  background-color: #fff1f0;
}


.dialog-content {
  font-size: 14px;
  color: #666;
  margin: 8px 0;
  display: block;
}

/* 添加空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 24px;
  gap: 16px;
}

.empty-text {
  color: #999;
  font-size: 14px;
}
</style> 